﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Snowdreamist.ComponentModel
{
    public static class ThreadSafeRandom
    {
        public static int Next()
        {
            if (_currentRandomObject == null)
                return AssignThreadStaticRandomObject().Next();
            return _currentRandomObject.Next();
        }

        public static double NextDouble()
        {
            if (_currentRandomObject == null)
                return AssignThreadStaticRandomObject().NextDouble();
            return _currentRandomObject.NextDouble();
        }

        public static void NextBytes(byte[] buffer)
        {
            if (_currentRandomObject == null)
                AssignThreadStaticRandomObject().NextBytes(buffer);
            _currentRandomObject.NextBytes(buffer);
        }

        #region private

        private static Random AssignThreadStaticRandomObject()
        {
            lock (_syncRoot)
            {
                _currentRandomObject = new Random(_randomSeed.Next());
                return _currentRandomObject;
            }
        }
        /// <summary>
        /// Thread static random object
        /// </summary>
        [ThreadStatic]
        private static Random _currentRandomObject;
        /// <summary>
        /// lock object
        /// </summary>
        private static readonly object _syncRoot = new object();
        /// <summary>
        /// Used to generate random object
        /// </summary>
        private static readonly Random _randomSeed = new Random();

        #endregion
    }
}
